#include"sock.h"


void ini_path6(struct sockaddr_in6 * addr , struct in6_addr* in6addr , int port)
{
    memset(addr,0,sizeof(struct sockaddr_in6));
    addr->sin6_family = AF_INET6;
    addr->sin6_addr = *in6addr;
    addr->sin6_port = htons(port);
}

int main(int argc , char ** argv)
{
    int sfd = socket(AF_INET6,SOCK_DGRAM,0);
    if(sfd == -1)
        errExit("socket");
    struct sockaddr_in6 claddr , addr;
    ini_path6(&addr, &in6addr_any,PORT_NUM);

    int len = sizeof(struct sockaddr_in6);
    if(bind(sfd,(struct sockaddr * ) &addr ,len ) == - 1)
        errExit("bind");
    
    char buf[BUF_SIZE];
    char claddrStr[BUF_SIZE];
    while(1){
        int numRead =  recvfrom(sfd,buf,BUF_SIZE,0,(struct sockaddr_in6 *) &claddr,&len) ;
        if(numRead  == -1 )
            errExit("recvfrom");

        if(inet_ntop(AF_INET6 , &claddr.sin6_addr,claddrStr,INET6_ADDRSTRLEN) ==NULL )
            printf("Couldn't convert client address to string\n");
        else
            printf("Server received %ld bytes from (%s, %u)\n",
                    numRead, claddrStr, ntohs(claddr.sin6_port));
            
        for(int i = 0 ;i < numRead; ++ i)
            buf[i] = toupper(buf[i]);
        if(sendto(sfd,buf,numRead,0,(struct sockaddr_in6 *)& claddr, len) == -1)
            fatal("sendto");
    }
    return 0;
}